<?php

class Db{
    private static $dbh=null;
    public static function init(){
        foreach (array("db_host","db_database","db_username","db_password") as $value)
        {
            if (!Util::config($value))
            {
                header("HTTP/1.1 500 Internal Server Error");
                echo $value."未设置";
                exit();
            }
        }
        try{
            self::$dbh=new PDO("mysql:host=".Util::config("db_host").";dbname=".Util::config("db_database"),Util::config("db_username"),Util::config("db_password"));
        }catch(PDOException $e){
            header("HTTP/1.1 500 Internal Server Error");
            echo $e->getMessage();
            exit();
        }
        self::$dbh->query("SET NAMES utf8");
    }
    public static function query($sql,$data=array(),$options=array()){
        if (self::$dbh===null){
            self::init();
        }

        $sth=self::$dbh->prepare($sql,$options);
        $res=$sth->execute($data);
        if (!$res){
            header("HTTP/1.1 500 Internal Server Error");
            echo 'db exe error';
            exit();
        }
        return $sth->fetchAll(PDO::FETCH_ASSOC);
    }
}